import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.border.TitledBorder;

public class LotteryGUI {
    private List<Record> records; // 新增抽奖记录列表
    private JFrame frame;
    private PrizePool prizePool;
    private JTextArea resultArea;
    private JButton startButton;
    private JTextField participantField;
    private JProgressBar progressBar;
    private ExecutorService executor;
    private BufferedImage backgroundImage;
    // 自定义字体，黄色加粗 20
    private Font customFont = new Font("微软雅黑", Font.BOLD, 20);
    // 钻石剑信息的字体，红色加粗 20
    private Font diamondSwordFont = new Font("微软雅黑", Font.BOLD, 20);
    private Color diamondSwordColor = Color.RED;
    // 其他奖品信息的字体，黄色加粗 20
    private Color otherPrizeColor = Color.YELLOW;
    private Timer progressBarTimer; // 用于进度条闪烁效果的定时器

    public LotteryGUI() {
        prizePool = new PrizePool();
        records = new ArrayList<>(); // 初始化记录列表
        try {
            backgroundImage = ImageIO.read(new File("images/lottery_background.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        initialize();
    }

    private void initialize() {
        frame = new JFrame("我的世界游戏武器抽奖系统");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout(10, 10));

        // 使窗口居中
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screenSize.width - frame.getWidth()) / 2;
        int y = (screenSize.height - frame.getHeight()) / 2;
        frame.setLocation(x, y);

        // 自定义背景面板
        JPanel backgroundPanel = new JPanel(new BorderLayout(10, 10)) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (backgroundImage != null) {
                    Graphics2D g2d = (Graphics2D) g;
                    int width = getWidth();
                    int height = getHeight();
                    g2d.drawImage(backgroundImage, 0, 0, width, height, this);
                }
            }
        };

        // 顶部面板 - 标题和输入
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        topPanel.setOpaque(false);
        JLabel participantLabel = new JLabel("参与者数量:");
        participantLabel.setFont(customFont);
        participantLabel.setForeground(otherPrizeColor);
        topPanel.add(participantLabel);
        participantField = new JTextField(10);
        participantField.setFont(customFont);
        // 设置输入字体颜色为红色
        participantField.setForeground(Color.RED);
        topPanel.add(participantField);

        startButton = new JButton("开始抽奖");
        startButton.setFont(customFont);
        startButton.setForeground(otherPrizeColor);
        startButton.addActionListener(new StartButtonListener());
        topPanel.add(startButton);

        progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        progressBar.setFont(customFont);
        topPanel.add(progressBar);

        backgroundPanel.add(topPanel, BorderLayout.NORTH);

        // 中间面板 - 奖品信息
        JPanel prizePanel = new JPanel(new GridLayout(1, 4, 10, 10));
        prizePanel.setOpaque(false);
        TitledBorder prizeTitleBorder = BorderFactory.createTitledBorder("奖品设置");
        prizeTitleBorder.setTitleFont(customFont);
        prizeTitleBorder.setTitleColor(otherPrizeColor);
        prizePanel.setBorder(prizeTitleBorder);

        prizePanel.add(createPrizePanelWithImage("一等奖", "钻石剑", "攻击力+10，耐久度1500", 1, "images/diamond_sword.png"));
        prizePanel.add(createPrizePanelWithImage("二等奖", "铁剑", "攻击力+6，耐久度500", 3, "images/iron_sword.png"));
        prizePanel.add(createPrizePanelWithImage("三等奖", "石剑", "攻击力+4，耐久度200", 7, "images/stone_sword.png"));
        prizePanel.add(createPrizePanelWithImage("参与奖", "木棍", "攻击力+1，耐久度50", -1, "images/stick.png"));

        backgroundPanel.add(prizePanel, BorderLayout.CENTER);

        // 底部面板 - 结果显示
        resultArea = new JTextArea();
        resultArea.setEditable(false);
        resultArea.setFont(customFont);
        resultArea.setForeground(otherPrizeColor);
        JScrollPane scrollPane = new JScrollPane(resultArea);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        resultArea.setOpaque(false);
        TitledBorder resultTitleBorder = BorderFactory.createTitledBorder("抽奖结果");
        resultTitleBorder.setTitleFont(customFont);
        resultTitleBorder.setTitleColor(otherPrizeColor);
        scrollPane.setBorder(resultTitleBorder);
        backgroundPanel.add(scrollPane, BorderLayout.SOUTH);

        frame.add(backgroundPanel, BorderLayout.CENTER);

        // 监听窗口大小改变事件，重绘背景图
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                backgroundPanel.repaint();
            }
        });

        frame.setVisible(true);
    }

    private JPanel createPrizePanelWithImage(String level, String name, String desc, int count, String imageName) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));

        // 加载图片
        ImageIcon icon = loadImage(imageName);
        JLabel imageLabel = new JLabel();
        if (icon != null) {
            // 缩放图片以适应界面
            Image scaledImage = icon.getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(scaledImage));
            imageLabel.setHorizontalAlignment(JLabel.CENTER);
        } else {
            imageLabel.setText("图片加载失败");
        }
        panel.add(imageLabel, BorderLayout.CENTER);

        // 文字信息面板
        JPanel infoPanel = new JPanel(new GridLayout(3, 1));
        infoPanel.setOpaque(false);
        JLabel titleLabel = new JLabel(level + ": " + name, JLabel.CENTER);
        JTextArea descArea = new JTextArea(desc);
        descArea.setEditable(false);
        descArea.setLineWrap(true);
        descArea.setOpaque(false);
        JLabel countLabel = new JLabel(count == -1 ? "无限量" : ("数量: " + count), JLabel.CENTER);

        if ("钻石剑".equals(name)) {
            titleLabel.setFont(diamondSwordFont);
            titleLabel.setForeground(diamondSwordColor);
            descArea.setFont(diamondSwordFont);
            descArea.setForeground(diamondSwordColor);
            countLabel.setFont(diamondSwordFont);
            countLabel.setForeground(diamondSwordColor);
        } else {
            titleLabel.setFont(customFont);
            titleLabel.setForeground(otherPrizeColor);
            descArea.setFont(customFont);
            descArea.setForeground(otherPrizeColor);
            countLabel.setFont(customFont);
            countLabel.setForeground(otherPrizeColor);
        }

        infoPanel.add(titleLabel);
        infoPanel.add(descArea);
        infoPanel.add(countLabel);

        panel.add(infoPanel, BorderLayout.SOUTH);

        return panel;
    }

    private ImageIcon loadImage(String imageName) {
        try {
            File imageFile = new File(imageName);
            if (imageFile.exists()) {
                return new ImageIcon(imageFile.getAbsolutePath());
            }
            System.err.println("无法加载图片: " + imageName);
            System.err.println("尝试查找路径: " + imageFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private class StartButtonListener implements ActionListener {
        private Map<String, Integer> firstPrizeStreak = new HashMap<>(); // 记录玩家连续获得一等奖的次数

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int participantCount = Integer.parseInt(participantField.getText());
                if (participantCount <= 0) {
                    JOptionPane.showMessageDialog(frame, "嘿，得输入个有效的参与者数量哦！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                startButton.setEnabled(false);
                resultArea.setText("");
                progressBar.setMaximum(participantCount);
                progressBar.setValue(0);

                executor = Executors.newFixedThreadPool(10);

                // 开始进度条闪烁效果
                progressBarTimer = new Timer(200, new ActionListener() {
                    private boolean isHighlighted = false;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (isHighlighted) {
                            progressBar.setForeground(Color.GREEN);
                        } else {
                            progressBar.setForeground(Color.RED);
                        }
                        isHighlighted = !isHighlighted;
                    }
                });
                progressBarTimer.start();

                // 创建并执行参与者线程
                for (int i = 1; i <= participantCount; i++) {
                    final int playerNum = i;
                    executor.execute(() -> {
                        Participant participant = new Participant("玩家" + playerNum, prizePool);
                        participant.run();

                        // 更新UI
                        SwingUtilities.invokeLater(() -> {
                            resultArea.append(participant.getParticipantName() + " 获得了 " +
                                    participant.getPrizeWon().getName() + "\n");
                            progressBar.setValue(progressBar.getValue() + 1);
                            records.add(new Record(participant.getParticipantName(),
                                    participant.getPrizeWon())); // 记录抽奖结果

                            // 检查是否连续获得一等奖
                            if ("一等奖".equals(participant.getPrizeWon().getName())) {
                                firstPrizeStreak.put(participant.getParticipantName(), firstPrizeStreak.getOrDefault(participant.getParticipantName(), 0) + 1);
                                if (firstPrizeStreak.get(participant.getParticipantName()) >= 3) {
                                    resultArea.append("哇哦！" + participant.getParticipantName() + " 简直是欧皇附体，连续获得了 " +
                                            firstPrizeStreak.get(participant.getParticipantName()) + " 个一等奖！\n");
                                }
                            } else {
                                firstPrizeStreak.put(participant.getParticipantName(), 0);
                            }

                            if (progressBar.getValue() == participantCount) {
                                progressBarTimer.stop(); // 停止进度条闪烁效果
                                progressBar.setForeground(Color.GREEN); // 最终设置为绿色
                                StringBuilder allResults = new StringBuilder();
                                allResults.append(showFinalResults(participantCount));
                                allResults.append(showRanking());
                                resultArea.append(allResults.toString());
                                // 将抽奖结果和排行榜写入文件
                                try (FileWriter writer = new FileWriter("Lottery results.txt")) {
                                    writer.write(allResults.toString());
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                                startButton.setEnabled(true);
                            }
                        });
                    });
                }

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(frame, "嘿，得输入个有效的数字哦！", "错误", JOptionPane.ERROR_MESSAGE);
                startButton.setEnabled(true);
            }
        }

        private String showRanking() {
            Map<String, Integer> firstPrizeMap = new HashMap<>();
            Map<String, Integer> secondPrizeMap = new HashMap<>();
            Map<String, Integer> thirdPrizeMap = new HashMap<>();
            Map<String, Integer> participationPrizeMap = new HashMap<>();

            for (Record record : records) {
                String username = record.getUsername();
                Prize prize = record.getPrize();
                String prizeName = prize.getName();

                switch (prizeName) {
                    case "一等奖":
                        firstPrizeMap.put(username, firstPrizeMap.getOrDefault(username, 0) + 1);
                        break;
                    case "二等奖":
                        secondPrizeMap.put(username, secondPrizeMap.getOrDefault(username, 0) + 1);
                        break;
                    case "三等奖":
                        thirdPrizeMap.put(username, thirdPrizeMap.getOrDefault(username, 0) + 1);
                        break;
                    case "参与奖":
                        participationPrizeMap.put(username, participationPrizeMap.getOrDefault(username, 0) + 1);
                        break;
                }
            }

            StringBuilder sb = new StringBuilder("\n===== 排行榜 =====\n");
            sb.append("一等奖排行榜:\n");
            appendRanking(sb, firstPrizeMap);
            sb.append("二等奖排行榜:\n");
            appendRanking(sb, secondPrizeMap);
            sb.append("三等奖排行榜:\n");
            appendRanking(sb, thirdPrizeMap);
            sb.append("参与奖排行榜:\n");
            appendRanking(sb, participationPrizeMap);

            return sb.toString();
        }

        private void appendRanking(StringBuilder sb, Map<String, Integer> rankingMap) {
            List<Map.Entry<String, Integer>> rankingList = new ArrayList<>(rankingMap.entrySet());
            rankingList.sort(Map.Entry.<String, Integer>comparingByValue().reversed());

            for (int i = 0; i < Math.min(5, rankingList.size()); i++) {
                Map.Entry<String, Integer> entry = rankingList.get(i);
                sb.append(i + 1).append(". ").append(entry.getKey()).append(": ").append(entry.getValue()).append(" 个\n");
            }
            sb.append("\n");
        }

        private String showFinalResults(int participantCount) {
            StringBuilder sb = new StringBuilder("\n===== 本次抽奖结果 =====\n");
            sb.append("参与抽奖的玩家数量为：").append(participantCount).append(" 人\n");

            List<Prize> prizes = prizePool.getPrizes();
            for (Prize prize : prizes) {
                sb.append(prize.getName()).append(": ")
                        .append(prize.getTotal() - prize.getRemaining()).append("/")
                        .append(prize.getTotal()).append("\n");
            }

            sb.append("参与奖(木棍): ").append(prizePool.getParticipationCount()).append("人\n");

            prizePool.reset(); // 重置奖品池以便下次抽奖
            return sb.toString();
        }
    }
}